import dayjs from 'dayjs'
const XLSX = require('xlsx')

//通过table导出数据
export function outPutForTable(tab) {

  exportExcel(table2csv(tab));

}

//通过Array导出数据
export function outPutForArray(arr, excelName) {
  exportExcel(arr, excelName)
}

//多sheet导出
export function outPutMoreSheet(arr, excelName = '导出.xlsx') {
  var sheets = [],
      blob
  arr.forEach(v=>{
    sheets.push({
      name : v.name,
      value : csv2sheet(v.value.join('\n'))
    })
  })
  blob = sheet2blob(sheets)
  openDownloadDialog(blob,excelName)
}

//csv转sheet
function csv2sheet(csv) {
  var sheet = {}
  csv = csv.split('\n')
  csv.forEach(function (row, i) {
    row = row.split('~!@#')
    if (i == 0) sheet['!ref'] = 'A1:' + String.fromCharCode(65 + row.length - 1) + (csv.length)
    row.forEach(function (col, j) {
      sheet[String.fromCharCode(65 + j) + (i + 1)] = { v: col }
    })
  })
  return sheet
}

//sheet转blob
function sheet2blob(sheets) {
  var workbook = {
    SheetNames: [],
    Sheets: {}
  }
  sheets.forEach(v=>{
    workbook.SheetNames.push(v.name)
    workbook.Sheets[v.name] = v.value
  })
  var wopts = {
    bookType: 'xlsx',
    bookSST: false,
    type: 'binary'
  };
  var wbout = XLSX.write(workbook, wopts);
  var blob = new Blob([s2ab(wbout)], { type: "application/octet-stream" });
  function s2ab(s) {
    var buf = new ArrayBuffer(s.length);
    var view = new Uint8Array(buf);
    for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
    return buf;
  }
  return blob;
}

//table转csv
function table2csv(table) {
  var csv = [];
  var theads = table[0].children[1].children[0];
  var tbody = table[1].children[1].children;
  var temp = [];
  for (let i = 0; i < theads.length; i++) {
    temp.push(theads[0].innerText);
  }
  temp.unshift();
  csv.push(temp.join('~!@#'));
  for (let i = 0; i < tbody.length; i++) {
    temp = [];
    var tds = tbody[i].getElementsByTagName("td");
    for (let j = 0; j < tds.length; j++) {
      temp.push(tbody[i].getElementsByTagName("td")[j].innerText);
    }
    temp.unshift();
    csv.push(temp.join('~!@#'));
  }
  csv.unshift();
  csv.shift();
  return csv.join('\n');
}

//弹出下载框
export function openDownloadDialog(url, saveName) {
  if (typeof url == 'object' && url instanceof Blob) {
    url = URL.createObjectURL(url);
  }
  var aLink = document.createElement('a');
  aLink.href = url;
  aLink.download = saveName || '';
  var event;
  if (window.MouseEvent) event = new MouseEvent('click');
  else {
    event = document.createEvent('MouseEvents');
    event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
  }
  aLink.dispatchEvent(event);
}

function exportExcel(csv, excelName = '导出.xlsx') {
  var sheet = csv2sheet(csv);
  var blob = sheet2blob([{
    name : 'sheet1',
    value : sheet
  }]);
  openDownloadDialog(blob, excelName)
}

//数组转csv
Array.prototype.getExcelArray = function (header, listStr) {
  var arr = []
  arr.push(header.join('~!@#'))
  this.forEach((val) => {
    var rowArr = []
    listStr.forEach((v, i) => {
      if (typeof v == 'object') {
        var str = '',
            type = v.type || 'list'
        if(type == 'list'){
          val[v.key].forEach((s, j) => {
            str += " " + s[v.val]
          })
        }
        if(type == 'obj')str = v.val[val[v.key]]
        if(type == 'date')str = dayjs(val[v.key]).format('YYYY-MM-DD')
        if(type == 'datetime' && val[v.key])str = dayjs(val[v.key]).format('YYYY-MM-DD hh:mm:ss')
        rowArr.push(str)
      } else {
        rowArr.push(val[v])
      }
    })
    arr.push(rowArr.join('~!@#'))
  })
  return arr
}